<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.7.1">
<title>Java API</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */
/* Uncomment @import statement below to use as custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}
audio,canvas,video{display:inline-block}
audio:not([controls]){display:none;height:0}
script{display:none!important}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
a{background:transparent}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*::before,*::after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.stretch{width:100%}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:none}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite::before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table}
.clearfix::after,.float-group::after{clear:both}
*:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed;word-wrap:break-word}
*:not(pre)>code.nobreak{word-wrap:normal}
*:not(pre)>code.nowrap{white-space:nowrap}
pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed}
em em{font-style:normal}
strong strong{font-weight:400}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menuref{color:#000}
.menuseq b:not(.caret),.menuref{font-weight:inherit}
.menuseq{word-spacing:-.02em}
.menuseq b.caret{font-size:1.25em;line-height:.8}
.menuseq i.caret{font-weight:bold;text-align:center;width:.45em}
b.button::before,b.button::after{position:relative;top:-1px;font-weight:400}
b.button::before{content:"[";padding:0 3px 0 2px}
b.button::after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table}
#header::after,#content::after,#footnotes::after,#footer::after{clear:both}
#content{margin-top:1.25em}
#content::before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}
#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span::before{content:"\00a0\2013\00a0"}
#header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark::before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber::after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #efefed;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}
@media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
#content{margin-bottom:.625em}
.sect1{padding-bottom:.625em}
@media screen and (min-width:768px){#content{margin-bottom:1.25em}
.sect1{padding-bottom:1.25em}}
.sect1:last-child{padding-bottom:0}
.sect1+.sect1{border-top:1px solid #efefed}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock.fit-content>caption.title{white-space:nowrap;width:0}
.paragraph.lead>p,#preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8}
.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1}
.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em}
.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal}
@media screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}
@media screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}
.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.listingblock>.content{position:relative}
.listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999}
.listingblock:hover code[data-lang]::before{display:block}
.listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:#999}
.listingblock.terminal pre .command:not([data-prompt])::before{content:"$"}
table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}
table.pyhltable td.code{padding-left:.75em;padding-right:0}
pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}
pre.pygments .lineno{display:inline-block;margin-right:.25em}
table.pyhltable .linenodiv{background:none!important;padding-right:0!important}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right}
.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)}
.quoteblock .quoteblock blockquote{padding:0 0 0 .75em}
.quoteblock .quoteblock blockquote::before{display:none}
.verseblock{margin:0 1em 1.25em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract{margin:0 1em 1.25em;display:block}
.quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center}
.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{word-spacing:0;line-height:1.6}
.quoteblock.abstract blockquote::before,.quoteblock.abstract p::before{display:none}
table.tableblock{max-width:100%;border-collapse:separate}
p.tableblock:last-child{margin-bottom:0}
td.tableblock>.content{margin-bottom:-1.25em}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all>thead>tr>.tableblock,table.grid-all>tbody>tr>.tableblock{border-width:0 1px 1px 0}
table.grid-all>tfoot>tr>.tableblock{border-width:1px 1px 0 0}
table.grid-cols>*>tr>.tableblock{border-width:0 1px 0 0}
table.grid-rows>thead>tr>.tableblock,table.grid-rows>tbody>tr>.tableblock{border-width:0 0 1px}
table.grid-rows>tfoot>tr>.tableblock{border-width:1px 0 0}
table.grid-all>*>tr>.tableblock:last-child,table.grid-cols>*>tr>.tableblock:last-child{border-right-width:0}
table.grid-all>tbody>tr:last-child>.tableblock,table.grid-all>thead:last-child>tr>.tableblock,table.grid-rows>tbody>tr:last-child>.tableblock,table.grid-rows>thead:last-child>tr>.tableblock{border-bottom-width:0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot,table.frame-ends{border-width:1px 0}
table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd){background:#f8f8f7}
table.stripes-none tr,table.stripes-odd tr:nth-of-type(even){background:none}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
td>div.verse{white-space:pre}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none}
ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em}
ul.unstyled,ol.unstyled{margin-left:0}
ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:.25em}
ul.inline{display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em}
ul.inline>li{margin-left:1.25em}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top}
.colist td:not([class]):first-child img{max-width:none}
.colist td:not([class]):last-child{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0}
.imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background-color:#00fafa}
.black{color:#000}
.black-background{background-color:#000}
.blue{color:#0000bf}
.blue-background{background-color:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background-color:#fa00fa}
.gray{color:#606060}
.gray-background{background-color:#7d7d7d}
.green{color:#006000}
.green-background{background-color:#007d00}
.lime{color:#00bf00}
.lime-background{background-color:#00fa00}
.maroon{color:#600000}
.maroon-background{background-color:#7d0000}
.navy{color:#000060}
.navy-background{background-color:#00007d}
.olive{color:#606000}
.olive-background{background-color:#7d7d00}
.purple{color:#600060}
.purple-background{background-color:#7d007d}
.red{color:#bf0000}
.red-background{background-color:#fa0000}
.silver{color:#909090}
.silver-background{background-color:#bcbcbc}
.teal{color:#006060}
.teal-background{background-color:#007d7d}
.white{color:#bfbfbf}
.white-background{background-color:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background-color:#fafa00}
span.icon>.fa{cursor:default}
a span.icon>.fa{cursor:inherit}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]::after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@page{margin:1.25cm .75cm}
@media print{*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
html{font-size:80%}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]::after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span::before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]::before{display:block}
#footer{padding:0 .9375em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
@media print,amzn-kf8{#header>h1:first-child{margin-top:1.25rem}
.sect1{padding:0!important}
.sect1+.sect1{border:0}
#footer{background:none}
#footer-text{color:rgba(0,0,0,.6);font-size:.9em}}
@media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}}
</style>
</head>
<body id="java-api" class="article">
<div id="header">
<h1>Java API</h1>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Unresolved directive in index.asciidoc - include::../Versions.asciidoc[]</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_preface">Preface</h2>
<div class="sectionbody">
<div class="paragraph">
<p>deprecated[7.0.0, The <code>TransportClient</code> is deprecated in favour of the {java-rest}/java-rest-high.html[Java High Level REST Client] and will be removed in Elasticsearch 8.0. The {java-rest}/java-rest-high-level-migration.html[migration guide] describes all the steps needed to migrate.]</p>
</div>
<div class="paragraph">
<p>This section describes the Java API that Elasticsearch provides. All
Elasticsearch operations are executed using a
<a href="#client">Client</a> object. All
operations are completely asynchronous in nature (either accepts a
listener, or returns a future).</p>
</div>
<div class="paragraph">
<p>Additionally, operations on a client may be accumulated and executed in
<a href="#java-docs-bulk">Bulk</a>.</p>
</div>
<div class="paragraph">
<p>Note, all the APIs are exposed through the
Java API (actually, the Java API is used internally to execute them).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_javadoc">Javadoc</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The javadoc for the transport client can be found at {transport-client-javadoc}/index.html.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_maven_repository">Maven Repository</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Elasticsearch is hosted on
<a href="http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22elasticsearch%22">Maven
Central</a>.</p>
</div>
<div class="paragraph">
<p>For example, you can define the latest version in your <code>pom.xml</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>{version}</version>
</dependency></code></pre>
</div>
</div>
<div class="sect2">
<h3 id="java-transport-usage-maven-lucene">Lucene Snapshot repository</h3>
<div class="paragraph">
<p>The very first releases of any major version (like a beta), might have been built on top of a Lucene Snapshot version.
In such a case you will be unable to resolve the Lucene dependencies of the client.</p>
</div>
<div class="paragraph">
<p>For example, if you want to use the <code>6.0.0-beta1</code> version which depends on Lucene <code>7.0.0-snapshot-00142c9</code>, you must
define the following repository.</p>
</div>
<div class="paragraph">
<p>For Maven:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><repository>
    <id>elastic-lucene-snapshots</id>
    <name>Elastic Lucene Snapshots</name>
    <url>http://s3.amazonaws.com/download.elasticsearch.org/lucenesnapshots/00142c9</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>false</enabled></snapshots>
</repository></code></pre>
</div>
</div>
<div class="paragraph">
<p>For Gradle:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">maven {
    url 'http://s3.amazonaws.com/download.elasticsearch.org/lucenesnapshots/00142c9'
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_log4j_2_logger">Log4j 2 Logger</h3>
<div class="paragraph">
<p>You need to also include Log4j 2 dependencies:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.9.1</version>
</dependency></code></pre>
</div>
</div>
<div class="paragraph">
<p>And also provide a Log4j 2 configuration file in your classpath.
For example, you can add in your <code>src/main/resources</code> project dir a <code>log4j2.properties</code> file like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-properties" data-lang="properties">appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%d{ISO8601}][%-5p][%-25c] %marker%m%n

rootLogger.level = info
rootLogger.appenderRef.console.ref = console</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_using_another_logger">Using another Logger</h3>
<div class="paragraph">
<p>If you want to use another logger than Log4j 2, you can use <a href="http://www.slf4j.org/">SLF4J</a> bridge to do that:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.24</version>
</dependency></code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="http://www.slf4j.org/manual.html">This page</a> lists implementations you can use. Pick your favorite logger
and add it as a dependency. As an example, we will use the <code>slf4j-simple</code> logger:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.21</version>
</dependency></code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_dealing_with_jar_dependency_conflicts">Dealing with JAR dependency conflicts</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you want to use Elasticsearch in your Java application, you may have to deal with version conflicts with third party
dependencies like Guava and Joda.  For instance, perhaps Elasticsearch uses Joda 2.8, while your code uses Joda 2.1.</p>
</div>
<div class="paragraph">
<p>You have two choices:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The simplest solution is to upgrade. Newer module versions are likely to have fixed old bugs.
The further behind you fall, the harder it will be to upgrade later. Of course, it is possible that you are using a
third party dependency that in turn depends on an outdated version of a package, which prevents you from upgrading.</p>
</li>
<li>
<p>The second option is to relocate the troublesome dependencies and to shade them either with your own application
or with Elasticsearch and any plugins needed by the Elasticsearch client.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The <a href="https://www.elastic.co/blog/to-shade-or-not-to-shade">"To shade or not to shade" blog post</a> describes
all the steps for doing so.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_embedding_jar_with_dependencies">Embedding jar with dependencies</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you want to create a single jar containing your application and all dependencies, you should not
use <code>maven-assembly-plugin</code> for that because it can not deal with <code>META-INF/services</code> structure which is
required by Lucene jars.</p>
</div>
<div class="paragraph">
<p>Instead, you can use <code>maven-shade-plugin</code> and configure it as follow:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;plugin&gt;
    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
    &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;
    &lt;version&gt;2.4.1&lt;/version&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;phase&gt;package&lt;/phase&gt;
            &lt;goals&gt;&lt;goal&gt;shade&lt;/goal&gt;&lt;/goals&gt;
            &lt;configuration&gt;
                &lt;transformers&gt;
                    &lt;transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/&gt;
                &lt;/transformers&gt;
            &lt;/configuration&gt;
        &lt;/execution&gt;
    &lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that if you have a <code>main</code> class you want to automatically call when running <code>java -jar yourjar.jar</code>, just add
it to the <code>transformers</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"&gt;
    &lt;mainClass&gt;org.elasticsearch.demo.Generate&lt;/mainClass&gt;
&lt;/transformer&gt;</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="client">Client</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can use the <strong>Java client</strong> in multiple ways:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Perform standard <a href="#java-docs-index">index</a>, <a href="#java-docs-get">get</a>,
<a href="#java-docs-delete">delete</a> and <a href="#java-search">search</a> operations on an
existing cluster</p>
</li>
<li>
<p>Perform administrative tasks on a running cluster</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Obtaining an Elasticsearch <code>Client</code> is simple. The most common way to
get a client is by creating a <a href="#transport-client"><code>TransportClient</code></a>
that connects to a cluster.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<div class="title">Important</div>
</td>
<td class="content">
<div class="paragraph">
<p>The client must have the same major version (e.g. <code>2.x</code>, or <code>5.x</code>) as the
nodes in the cluster. Clients may connect to clusters which have a different
minor version (e.g. <code>2.3.x</code>) but it is possible that new functionality may not
be supported.  Ideally, the client should have the same version as the
cluster.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="transport-client">Transport Client</h3>
<div class="paragraph">
<p>deprecated[7.0.0, The <code>TransportClient</code> is deprecated in favour of the {java-rest}/java-rest-high.html[Java High Level REST Client] and will be removed in Elasticsearch 8.0. The {java-rest}/java-rest-high-level-migration.html[migration guide] describes all the steps needed to migrate.]</p>
</div>
<div class="paragraph">
<p>The <code>TransportClient</code> connects remotely to an Elasticsearch cluster
using the transport module. It does not join the cluster, but simply
gets one or more initial transport addresses and communicates with them
in round robin fashion on each action (though most actions will probably
be "two hop" operations).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// on startup

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
        .addTransportAddress(new TransportAddress(InetAddress.getByName("host1"), 9300))
        .addTransportAddress(new TransportAddress(InetAddress.getByName("host2"), 9300));

// on shutdown

client.close();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you have to set the cluster name if you use one different than
"elasticsearch":</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Settings settings = Settings.builder()
        .put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings);
//Add transport addresses and do something with the client...</code></pre>
</div>
</div>
<div class="paragraph">
<p>The Transport client comes with a cluster sniffing feature which
allows it to dynamically add new hosts and remove old ones.
When sniffing is enabled, the transport client will connect to the nodes in its
internal node list, which is built via calls to <code>addTransportAddress</code>.
After this, the client will call the internal cluster state API on those nodes
to discover available data nodes. The internal node list of the client will
be replaced with those data nodes only. This list is refreshed every five seconds by default.
Note that the IP addresses the sniffer connects to are the ones declared as the 'publish'
address in those node&#8217;s Elasticsearch config.</p>
</div>
<div class="paragraph">
<p>Keep in mind that the list might possibly not include the original node it connected to
if that node is not a data node. If, for instance, you initially connect to a
master node, after sniffing, no further requests will go to that master node,
but rather to any data nodes instead. The reason the transport client excludes non-data
nodes is to avoid sending search traffic to master only nodes.</p>
</div>
<div class="paragraph">
<p>In order to enable sniffing, set <code>client.transport.sniff</code> to <code>true</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Settings settings = Settings.builder()
        .put("client.transport.sniff", true).build();
TransportClient client = new PreBuiltTransportClient(settings);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Other transport client level settings include:</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Parameter</th>
<th class="tableblock halign-left valign-top">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>client.transport.ignore_cluster_name</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Set to <code>true</code> to ignore cluster
name validation of connected nodes. (since 0.19.4)</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>client.transport.ping_timeout</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The time to wait for a ping response
from a node. Defaults to <code>5s</code>.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>client.transport.nodes_sampler_interval</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">How often to sample / ping
the nodes listed and connected. Defaults to <code>5s</code>.</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect2">
<h3 id="client-connected-to-client-node">Connecting a Client to a Coordinating Only Node</h3>
<div class="paragraph">
<p>You can start locally a {ref}/modules-node.html#coordinating-only-node[Coordinating Only Node]
and then simply create a <a href="#transport-client"><code>TransportClient</code></a> in your
application which connects to this Coordinating Only Node.</p>
</div>
<div class="paragraph">
<p>This way, the coordinating only node will be able to load whatever plugin you
need (think about discovery plugins for example).</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="java-docs">Document APIs</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This section describes the following CRUD APIs:</p>
</div>
<div class="ulist">
<div class="title">Single document APIs</div>
<ul>
<li>
<p><a href="#java-docs-index">Index API</a></p>
</li>
<li>
<p><a href="#java-docs-get">Get API</a></p>
</li>
<li>
<p><a href="#java-docs-delete">Delete API</a></p>
</li>
<li>
<p><a href="#java-docs-delete-by-query">Delete By Query API</a></p>
</li>
<li>
<p><a href="#java-docs-update">Update API</a></p>
</li>
</ul>
</div>
<div class="ulist">
<div class="title">Multi-document APIs</div>
<ul>
<li>
<p><a href="#java-docs-multi-get">Multi Get API</a></p>
</li>
<li>
<p><a href="#java-docs-bulk">Bulk API</a></p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
All CRUD APIs are single-index APIs. The <code>index</code> parameter accepts a single
index name, or an <code>alias</code> which points to a single index.
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="java-docs-index">Index API</h3>
<div class="paragraph">
<p>The index API allows one to index a typed JSON document into a specific
index and make it searchable.</p>
</div>
<div class="sect3">
<h4 id="java-docs-index-generate">Generate JSON document</h4>
<div class="paragraph">
<p>There are several different ways of generating a JSON document:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Manually (aka do it yourself) using native <code>byte[]</code> or as a <code>String</code></p>
</li>
<li>
<p>Using a <code>Map</code> that will be automatically converted to its JSON
equivalent</p>
</li>
<li>
<p>Using a third party library to serialize your beans such as
<a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a></p>
</li>
<li>
<p>Using built-in helpers XContentFactory.jsonBuilder()</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Internally, each type is converted to <code>byte[]</code> (so a String is converted
to a <code>byte[]</code>). Therefore, if the object is in this form already, then
use it. The <code>jsonBuilder</code> is highly optimized JSON generator that
directly constructs a <code>byte[]</code>.</p>
</div>
<div class="sect4">
<h5 id="java-docs-index-generate-diy">Do It Yourself</h5>
<div class="paragraph">
<p>Nothing really difficult here but note that you will have to encode
dates according to the
{ref}/mapping-date-format.html[Date Format].</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="java-docs-index-generate-using-map">Using Map</h5>
<div class="paragraph">
<p>Map is a key:values pair collection. It represents a JSON structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Map&lt;String, Object&gt; json = new HashMap&lt;String, Object&gt;();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="java-docs-index-generate-beans">Serialize your beans</h5>
<div class="paragraph">
<p>You can use <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> to serialize
your beans to JSON. Please add <a href="http://search.maven.org/#search%7Cga%7C1%7Cjackson-databind">Jackson Databind</a>
 to your project. Then you can use <code>ObjectMapper</code> to serialize your beans:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import com.fasterxml.jackson.databind.*;

// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse

// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="java-docs-index-generate-helpers">Use Elasticsearch helpers</h5>
<div class="paragraph">
<p>Elasticsearch provides built-in helpers to generate JSON content.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import static org.elasticsearch.common.xcontent.XContentFactory.*;

XContentBuilder builder = jsonBuilder()
    .startObject()
        .field("user", "kimchy")
        .field("postDate", new Date())
        .field("message", "trying out Elasticsearch")
    .endObject()</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you can also add arrays with <code>startArray(String)</code> and
<code>endArray()</code> methods. By the way, the <code>field</code> method<br>
 accepts many object types. You can directly pass numbers, dates and even
other XContentBuilder objects.</p>
</div>
<div class="paragraph">
<p>If you need to see the generated JSON content, you can use the
<code>string()</code> method.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">String json = builder.string();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-docs-index-doc">Index document</h4>
<div class="paragraph">
<p>The following example indexes a JSON document into an index called
twitter, under a type called tweet, with id valued 1:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import static org.elasticsearch.common.xcontent.XContentFactory.*;

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        .get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you can also index your documents as JSON String and that you
don&#8217;t have to give an ID:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";

IndexResponse response = client.prepareIndex("twitter", "tweet")
        .setSource(json, XContentType.JSON)
        .get();</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>IndexResponse</code> object will give you a report:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
// status has stored current instance statement.
RestStatus status = response.status();</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on the index operation, check out the REST
{ref}/docs-index_.html[index] docs.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-get">Get API</h3>
<div class="paragraph">
<p>The get API allows to get a typed JSON document from the index based on
its id. The following example gets a JSON document from an index called
twitter, under a type called tweet, with id valued 1:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">GetResponse response = client.prepareGet("twitter", "tweet", "1").get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on the get operation, check out the REST
{ref}/docs-get.html[get] docs.</p>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-delete">Delete API</h3>
<div class="paragraph">
<p>The delete API allows one to delete a typed JSON document from a specific
index based on its id. The following example deletes the JSON document
from an index called twitter, under a type called tweet, with id valued
1:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on the delete operation, check out the
{ref}/docs-delete.html[delete API] docs.</p>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-delete-by-query">Delete By Query API</h3>
<div class="paragraph">
<p>The delete by query API allows one to delete a given set of documents based on
the result of a query:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">BulkByScrollResponse response =
    DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
        .filter(QueryBuilders.matchQuery("gender", "male")) <b class="conum">(1)</b>
        .source("persons")                                  <b class="conum">(2)</b>
        .get();                                             <b class="conum">(3)</b>

long deleted = response.getDeleted();                       <b class="conum">(4)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>query</p>
</li>
<li>
<p>index</p>
</li>
<li>
<p>execute the operation</p>
</li>
<li>
<p>number of deleted documents</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>As it can be a long running operation, if you wish to do it asynchronously, you can call <code>execute</code> instead of <code>get</code>
and provide a listener like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
    .filter(QueryBuilders.matchQuery("gender", "male"))                  <b class="conum">(1)</b>
    .source("persons")                                                   <b class="conum">(2)</b>
    .execute(new ActionListener&lt;BulkByScrollResponse&gt;() {           <b class="conum">(3)</b>
        @Override
        public void onResponse(BulkByScrollResponse response) {
            long deleted = response.getDeleted();                        <b class="conum">(4)</b>
        }
        @Override
        public void onFailure(Exception e) {
            // Handle the exception
        }
    });</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>query</p>
</li>
<li>
<p>index</p>
</li>
<li>
<p>listener</p>
</li>
<li>
<p>number of deleted documents</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-update">Update API</h3>
<div class="paragraph">
<p>You can either create an <code>UpdateRequest</code> and send it to the client:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("index");
updateRequest.type("type");
updateRequest.id("1");
updateRequest.doc(jsonBuilder()
        .startObject()
            .field("gender", "male")
        .endObject());
client.update(updateRequest).get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can use <code>prepareUpdate()</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.prepareUpdate("ttl", "doc", "1")
        .setScript(new Script("ctx._source.gender = \"male\"" &lt;1&gt; , ScriptService.ScriptType.INLINE, null, null))
        .get();

client.prepareUpdate("ttl", "doc", "1")
        .setDoc(jsonBuilder()               <b class="conum">(2)</b>
            .startObject()
                .field("gender", "male")
            .endObject())
        .get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Your script. It could also be a locally stored script name.
In that case, you&#8217;ll need to use <code>ScriptService.ScriptType.FILE</code></p>
</li>
<li>
<p>Document which will be merged to the existing one.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>Note that you can&#8217;t provide both <code>script</code> and <code>doc</code>.</p>
</div>
<div class="sect3">
<h4 id="java-docs-update-api-script">Update by script</h4>
<div class="paragraph">
<p>The update API allows to update a document based on a script provided:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">UpdateRequest updateRequest = new UpdateRequest("ttl", "doc", "1")
        .script(new Script("ctx._source.gender = \"male\""));
client.update(updateRequest).get();</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-docs-update-api-merge-docs">Update by merging documents</h4>
<div class="paragraph">
<p>The update API also support passing a partial document, which will be merged into the existing document (simple
recursive merge, inner merging of objects, replacing core "keys/values" and arrays). For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">UpdateRequest updateRequest = new UpdateRequest("index", "type", "1")
        .doc(jsonBuilder()
            .startObject()
                .field("gender", "male")
            .endObject());
client.update(updateRequest).get();</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-docs-update-api-upsert">Upsert</h4>
<div class="paragraph">
<p>There is also support for <code>upsert</code>. If the document does not exist, the content of the <code>upsert</code>
element will be used to index the fresh doc:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">IndexRequest indexRequest = new IndexRequest("index", "type", "1")
        .source(jsonBuilder()
            .startObject()
                .field("name", "Joe Smith")
                .field("gender", "male")
            .endObject());
UpdateRequest updateRequest = new UpdateRequest("index", "type", "1")
        .doc(jsonBuilder()
            .startObject()
                .field("gender", "male")
            .endObject())
        .upsert(indexRequest);              <b class="conum">(1)</b>
client.update(updateRequest).get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>If the document does not exist, the one in <code>indexRequest</code> will be added</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>If the document <code>index/type/1</code> already exists, we will have after this operation a document like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-js" data-lang="js">{
    "name"  : "Joe Dalton",
    "gender": "male"        <b class="conum">(1)</b>
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>This field is added by the update request</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>If it does not exist, we will have a new document:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-js" data-lang="js">{
    "name" : "Joe Smith",
    "gender": "male"
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-multi-get">Multi Get API</h3>
<div class="paragraph">
<p>The multi get API allows to get a list of documents based on their <code>index</code>, <code>type</code> and <code>id</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
    .add("twitter", "tweet", "1")           <b class="conum">(1)</b>
    .add("twitter", "tweet", "2", "3", "4") <b class="conum">(2)</b>
    .add("another", "type", "foo")          <b class="conum">(3)</b>
    .get();

for (MultiGetItemResponse itemResponse : multiGetItemResponses) { <b class="conum">(4)</b>
    GetResponse response = itemResponse.getResponse();
    if (response.isExists()) {                      <b class="conum">(5)</b>
        String json = response.getSourceAsString(); <b class="conum">(6)</b>
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>get by a single id</p>
</li>
<li>
<p>or by a list of ids for the same index / type</p>
</li>
<li>
<p>you can also get from another index</p>
</li>
<li>
<p>iterate over the result set</p>
</li>
<li>
<p>you can check if the document exists</p>
</li>
<li>
<p>access to the <code>_source</code> field</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>For more information on the multi get operation, check out the REST
{ref}/docs-multi-get.html[multi get] docs.</p>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-bulk">Bulk API</h3>
<div class="paragraph">
<p>The bulk API allows one to index and delete several documents in a
single request. Here is a sample usage:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import static org.elasticsearch.common.xcontent.XContentFactory.*;

BulkRequestBuilder bulkRequest = client.prepareBulk();

// either use client#prepare, or use Requests# to directly build index/delete requests
bulkRequest.add(client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        );

bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                    .endObject()
                  )
        );

BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
    // process failures by iterating through each bulk response item
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-docs-bulk-processor">Using Bulk Processor</h3>
<div class="paragraph">
<p>The <code>BulkProcessor</code> class offers a simple interface to flush bulk operations automatically based on the number or size
of requests, or after a given period.</p>
</div>
<div class="paragraph">
<p>To use it, first create a <code>BulkProcessor</code> instance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;

BulkProcessor bulkProcessor = BulkProcessor.builder(
        client,  <b class="conum">(1)</b>
        new BulkProcessor.Listener() {
            @Override
            public void beforeBulk(long executionId,
                                   BulkRequest request) { ... } <b class="conum">(2)</b>

            @Override
            public void afterBulk(long executionId,
                                  BulkRequest request,
                                  BulkResponse response) { ... } <b class="conum">(3)</b>

            @Override
            public void afterBulk(long executionId,
                                  BulkRequest request,
                                  Throwable failure) { ... } <b class="conum">(4)</b>
        })
        .setBulkActions(10000) <b class="conum">(5)</b>
        .setBulkSize(new ByteSizeValue(5, ByteSizeUnit.MB)) <b class="conum">(6)</b>
        .setFlushInterval(TimeValue.timeValueSeconds(5)) <b class="conum">(7)</b>
        .setConcurrentRequests(1) <b class="conum">(8)</b>
        .setBackoffPolicy(
            BackoffPolicy.exponentialBackoff(TimeValue.timeValueMillis(100), 3)) <b class="conum">(9)</b>
        .build();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Add your Elasticsearch client</p>
</li>
<li>
<p>This method is called just before bulk is executed. You can for example see the numberOfActions with
<code>request.numberOfActions()</code></p>
</li>
<li>
<p>This method is called after bulk execution. You can for example check if there was some failing requests
with <code>response.hasFailures()</code></p>
</li>
<li>
<p>This method is called when the bulk failed and raised a <code>Throwable</code></p>
</li>
<li>
<p>We want to execute the bulk every 10 000 requests</p>
</li>
<li>
<p>We want to flush the bulk every 5mb</p>
</li>
<li>
<p>We want to flush the bulk every 5 seconds whatever the number of requests</p>
</li>
<li>
<p>Set the number of concurrent requests. A value of 0 means that only a single request will be allowed to be
executed. A value of 1 means 1 concurrent request is allowed to be executed while accumulating new bulk requests.</p>
</li>
<li>
<p>Set a custom backoff policy which will initially wait for 100ms, increase exponentially and retries up to three
times. A retry is attempted whenever one or more bulk item requests have failed with an <code>EsRejectedExecutionException</code>
which indicates that there were too little compute resources available for processing the request. To disable backoff,
pass <code>BackoffPolicy.noBackoff()</code>.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>By default, <code>BulkProcessor</code>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>sets bulkActions to <code>1000</code></p>
</li>
<li>
<p>sets bulkSize to <code>5mb</code></p>
</li>
<li>
<p>does not set flushInterval</p>
</li>
<li>
<p>sets concurrentRequests to 1, which means an asynchronous execution of the flush operation.</p>
</li>
<li>
<p>sets backoffPolicy to an exponential backoff with 8 retries and a start delay of 50ms. The total wait time is roughly 5.1 seconds.</p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="java-docs-bulk-processor-requests">Add requests</h4>
<div class="paragraph">
<p>Then you can simply add your requests to the <code>BulkProcessor</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">bulkProcessor.add(new IndexRequest("twitter", "tweet", "1").source(/* your doc here */));
bulkProcessor.add(new DeleteRequest("twitter", "tweet", "2"));</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-docs-bulk-processor-close">Closing the Bulk Processor</h4>
<div class="paragraph">
<p>When all documents are loaded to the <code>BulkProcessor</code> it can be closed by using <code>awaitClose</code> or <code>close</code> methods:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">bulkProcessor.awaitClose(10, TimeUnit.MINUTES);</code></pre>
</div>
</div>
<div class="paragraph">
<p>or</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">bulkProcessor.close();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Both methods flush any remaining documents and disable all other scheduled flushes if they were scheduled by setting
<code>flushInterval</code>. If concurrent requests were enabled the <code>awaitClose</code> method waits for up to the specified timeout for
all bulk requests to complete then returns <code>true</code>, if the specified waiting time elapses before all bulk requests complete,
<code>false</code> is returned. The <code>close</code> method doesn&#8217;t wait for any remaining bulk requests to complete and exits immediately.</p>
</div>
</div>
<div class="sect3">
<h4 id="java-docs-bulk-processor-tests">Using Bulk Processor in tests</h4>
<div class="paragraph">
<p>If you are running tests with Elasticsearch and are using the <code>BulkProcessor</code> to populate your dataset
you should better set the number of concurrent requests to <code>0</code> so the flush operation of the bulk will be executed
in a synchronous manner:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">BulkProcessor bulkProcessor = BulkProcessor.builder(client, new BulkProcessor.Listener() { /* Listener methods */ })
        .setBulkActions(10000)
        .setConcurrentRequests(0)
        .build();

// Add your requests
bulkProcessor.add(/* Your requests */);

// Flush any remaining requests
bulkProcessor.flush();

// Or close the bulkProcessor if you don't need it anymore
bulkProcessor.close();

// Refresh your indices
client.admin().indices().prepareRefresh().get();

// Now you can start searching!
client.prepareSearch().get();</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="java-search">Search API</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The search API allows one to execute a search query and get back search hits
that match the query. It can be executed across one or more indices and
across one or more types. The query can be provided using the <a href="#java-query-dsl">query Java API</a>.
The body of the search request is built using the <code>SearchSourceBuilder</code>. Here is an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse response = client.prepareSearch("index1", "index2")
        .setTypes("type1", "type2")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(QueryBuilders.termQuery("multi", "test"))                 // Query
        .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
        .setFrom(0).setSize(60).setExplain(true)
        .get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that all parameters are optional. Here is the smallest search call
you can write:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// MatchAll on the whole cluster with all default options
SearchResponse response = client.prepareSearch().get();</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Although the Java API defines the additional search types QUERY_AND_FETCH and
        DFS_QUERY_AND_FETCH, these modes are internal optimizations and should not
        be specified explicitly by users of the API.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For more information on the search operation, check out the REST
{ref}/search.html[search] docs.</p>
</div>
<div class="sect2">
<h3 id="java-search-scrolling">Using scrolls in Java</h3>
<div class="paragraph">
<p>Read the {ref}/search-request-scroll.html[scroll documentation]
first!</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import static org.elasticsearch.index.query.QueryBuilders.*;

QueryBuilder qb = termQuery("multi", "test");

SearchResponse scrollResp = client.prepareSearch(test)
        .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
        .setScroll(new TimeValue(60000))
        .setQuery(qb)
        .setSize(100).get(); //max of 100 hits will be returned for each scroll
//Scroll until no hits are returned
do {
    for (SearchHit hit : scrollResp.getHits().getHits()) {
        //Handle the hit...
    }

    scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
} while(scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-search-msearch">MultiSearch API</h3>
<div class="paragraph">
<p>See {ref}/search-multi-search.html[MultiSearch API Query]
documentation</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchRequestBuilder srb1 = client
    .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);
SearchRequestBuilder srb2 = client
    .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);

MultiSearchResponse sr = client.prepareMultiSearch()
        .add(srb1)
        .add(srb2)
        .get();

// You will get all individual responses from MultiSearchResponse#getResponses()
long nbHits = 0;
for (MultiSearchResponse.Item item : sr.getResponses()) {
    SearchResponse response = item.getResponse();
    nbHits += response.getHits().getTotalHits();
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-search-aggs">Using Aggregations</h3>
<div class="paragraph">
<p>The following code shows how to add two aggregations within your search:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse sr = client.prepareSearch()
    .setQuery(QueryBuilders.matchAllQuery())
    .addAggregation(
            AggregationBuilders.terms("agg1").field("field")
    )
    .addAggregation(
            AggregationBuilders.dateHistogram("agg2")
                    .field("birth")
                    .dateHistogramInterval(DateHistogramInterval.YEAR)
    )
    .get();

// Get your facet results
Terms agg1 = sr.getAggregations().get("agg1");
Histogram agg2 = sr.getAggregations().get("agg2");</code></pre>
</div>
</div>
<div class="paragraph">
<p>See <a href="#java-aggs">Aggregations Java API</a>
documentation for details.</p>
</div>
</div>
<div class="sect2">
<h3 id="java-search-terminate-after">Terminate After</h3>
<div class="paragraph">
<p>The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.
If set, you will be able to check if the operation terminated early by asking for <code>isTerminatedEarly()</code> in the
<code>SearchResponse</code> onject:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse sr = client.prepareSearch(INDEX)
    .setTerminateAfter(1000)    <b class="conum">(1)</b>
    .get();

if (sr.isTerminatedEarly()) {
    // We finished early
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Finish after 1000 docs</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="java-search-template">Search Template</h3>
<div class="paragraph">
<p>See {ref}/search-template.html[Search Template] documentation</p>
</div>
<div class="paragraph">
<p>Define your template parameters as a <code>Map&lt;String,Object&gt;</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Map&lt;String, Object&gt; template_params = new HashMap&lt;&gt;();
template_params.put("param_gender", "male");</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use your stored search templates in <code>config/scripts</code>.
For example, if you have a file named <code>config/scripts/template_gender.mustache</code> containing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-js" data-lang="js">{
    "query" : {
        "match" : {
            "gender" : "{{param_gender}}"
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Create your search template request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse sr = new SearchTemplateRequestBuilder(client)
    .setScript("template_gender")                 <b class="conum">(1)</b>
    .setScriptType(ScriptService.ScriptType.FILE) <b class="conum">(2)</b>
    .setScriptParams(template_params)             <b class="conum">(3)</b>
    .setRequest(new SearchRequest())              <b class="conum">(4)</b>
    .get()                                        <b class="conum">(5)</b>
    .getResponse();                               <b class="conum">(6)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>template name</p>
</li>
<li>
<p>template stored on disk in <code>gender_template.mustache</code></p>
</li>
<li>
<p>parameters</p>
</li>
<li>
<p>set the execution context (ie. define the index name here)</p>
</li>
<li>
<p>execute and get the template response</p>
</li>
<li>
<p>get from the template response the search response itself</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>You can also store your template in the cluster state:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().cluster().preparePutStoredScript()
    .setScriptLang("mustache")
    .setId("template_gender")
    .setSource(new BytesArray(
        "{\n" +
        "    \"query\" : {\n" +
        "        \"match\" : {\n" +
        "            \"gender\" : \"{{param_gender}}\"\n" +
        "        }\n" +
        "    }\n" +
        "}")).get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>To execute a stored templates, use <code>ScriptService.ScriptType.STORED</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse sr = new SearchTemplateRequestBuilder(client)
        .setScript("template_gender")                       <b class="conum">(1)</b>
        .setScriptType(ScriptType.STORED)     <b class="conum">(2)</b>
        .setScriptParams(template_params)                   <b class="conum">(3)</b>
        .setRequest(new SearchRequest())                    <b class="conum">(4)</b>
        .get()                                              <b class="conum">(5)</b>
        .getResponse();                                     <b class="conum">(6)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>template name</p>
</li>
<li>
<p>template stored in the cluster state</p>
</li>
<li>
<p>parameters</p>
</li>
<li>
<p>set the execution context (ie. define the index name here)</p>
</li>
<li>
<p>execute and get the template response</p>
</li>
<li>
<p>get from the template response the search response itself</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>You can also execute inline templates:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">sr = new SearchTemplateRequestBuilder(client)
        .setScript("{\n" +                                  <b class="conum">(1)</b>
                "        \"query\" : {\n" +
                "            \"match\" : {\n" +
                "                \"gender\" : \"{{param_gender}}\"\n" +
                "            }\n" +
                "        }\n" +
                "}")
        .setScriptType(ScriptType.INLINE)    <b class="conum">(2)</b>
        .setScriptParams(template_params)                  <b class="conum">(3)</b>
        .setRequest(new SearchRequest())                   <b class="conum">(4)</b>
        .get()                                             <b class="conum">(5)</b>
        .getResponse();                                    <b class="conum">(6)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>template name</p>
</li>
<li>
<p>template is passed inline</p>
</li>
<li>
<p>parameters</p>
</li>
<li>
<p>set the execution context (ie. define the index name here)</p>
</li>
<li>
<p>execute and get the template response</p>
</li>
<li>
<p>get from the template response the search response itself</p>
</li>
</ol>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="java-aggs">Aggregations</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Elasticsearch provides a full Java API to play with aggregations. See the
{ref}/search-aggregations.html[Aggregations guide].</p>
</div>
<div class="paragraph">
<p>Use the factory for aggregation builders (<code>AggregationBuilders</code>) and add each aggregation
you want to compute when querying and add it to your search request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse sr = node.client().prepareSearch()
        .setQuery( /* your query */ )
        .addAggregation( /* add an aggregation */ )
        .execute().actionGet();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you can add more than one aggregation. See
{ref}/search-search.html[Search Java API] for details.</p>
</div>
<div class="paragraph">
<p>To build aggregation requests, use <code>AggregationBuilders</code> helpers. Just import them
in your class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.AggregationBuilders;</code></pre>
</div>
</div>
<div class="sect2">
<h3 id="_structuring_aggregations">Structuring aggregations</h3>
<div class="paragraph">
<p>As explained in the
{ref}/search-aggregations.html[Aggregations guide], you can define
sub aggregations inside an aggregation.</p>
</div>
<div class="paragraph">
<p>An aggregation could be a metrics aggregation or a bucket aggregation.</p>
</div>
<div class="paragraph">
<p>For example, here is a 3 levels aggregation composed of:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Terms aggregation (bucket)</p>
</li>
<li>
<p>Date Histogram aggregation (bucket)</p>
</li>
<li>
<p>Average aggregation (metric)</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SearchResponse sr = node.client().prepareSearch()
    .addAggregation(
        AggregationBuilders.terms("by_country").field("country")
        .subAggregation(AggregationBuilders.dateHistogram("by_year")
            .field("dateOfBirth")
            .dateHistogramInterval(DateHistogramInterval.YEAR)
            .subAggregation(AggregationBuilders.avg("avg_children").field("children"))
        )
    )
    .execute().actionGet();</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_metrics_aggregations">Metrics aggregations</h3>
<div class="sect3">
<h4 id="java-aggs-metrics-min">Min Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-min-aggregation.html[Min Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">MinAggregationBuilder aggregation =
        AggregationBuilders
                .min("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.min.Min;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Min agg = sr.getAggregations().get("agg");
double value = agg.getValue();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-max">Max Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-max-aggregation.html[Max Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_2">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">MaxAggregationBuilder aggregation =
        AggregationBuilders
                .max("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_2">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.max.Max;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Max agg = sr.getAggregations().get("agg");
double value = agg.getValue();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-sum">Sum Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-sum-aggregation.html[Sum Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_3">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">SumAggregationBuilder aggregation =
        AggregationBuilders
                .sum("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_3">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.sum.Sum;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Sum agg = sr.getAggregations().get("agg");
double value = agg.getValue();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-avg">Avg Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-avg-aggregation.html[Avg Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_4">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AvgAggregationBuilder aggregation =
        AggregationBuilders
                .avg("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_4">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.avg.Avg;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Avg agg = sr.getAggregations().get("agg");
double value = agg.getValue();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-stats">Stats Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-stats-aggregation.html[Stats Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_5">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">StatsAggregationBuilder aggregation =
        AggregationBuilders
                .stats("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_5">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.stats.Stats;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Stats agg = sr.getAggregations().get("agg");
double min = agg.getMin();
double max = agg.getMax();
double avg = agg.getAvg();
double sum = agg.getSum();
long count = agg.getCount();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-extendedstats">Extended Stats Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-extendedstats-aggregation.html[Extended Stats Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_6">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ExtendedStatsAggregationBuilder aggregation =
        AggregationBuilders
                .extendedStats("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_6">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
ExtendedStats agg = sr.getAggregations().get("agg");
double min = agg.getMin();
double max = agg.getMax();
double avg = agg.getAvg();
double sum = agg.getSum();
long count = agg.getCount();
double stdDeviation = agg.getStdDeviation();
double sumOfSquares = agg.getSumOfSquares();
double variance = agg.getVariance();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-valuecount">Value Count Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-valuecount-aggregation.html[Value Count Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_7">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ValueCountAggregationBuilder aggregation =
        AggregationBuilders
                .count("agg")
                .field("height");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_7">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
ValueCount agg = sr.getAggregations().get("agg");
long value = agg.getValue();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-percentile">Percentile Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-percentile-aggregation.html[Percentile Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_8">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">PercentilesAggregationBuilder aggregation =
        AggregationBuilders
                .percentiles("agg")
                .field("height");</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can provide your own percentiles instead of using defaults:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">PercentilesAggregationBuilder aggregation =
        AggregationBuilders
                .percentiles("agg")
                .field("height")
                .percentiles(1.0, 5.0, 10.0, 20.0, 30.0, 75.0, 95.0, 99.0);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_8">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Percentiles agg = sr.getAggregations().get("agg");
// For each entry
for (Percentile entry : agg) {
    double percent = entry.getPercent();    // Percent
    double value = entry.getValue();        // Value

    logger.info("percent [{}], value [{}]", percent, value);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce for the first example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">percent [1.0], value [0.814338896154595]
percent [5.0], value [0.8761912455821302]
percent [25.0], value [1.173346540141847]
percent [50.0], value [1.5432023318692198]
percent [75.0], value [1.923915462033674]
percent [95.0], value [2.2273644908535335]
percent [99.0], value [2.284989339108279]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-percentile-rank">Percentile Ranks Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-percentile-rank-aggregation.html[Percentile Ranks Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_9">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">PercentileRanksAggregationBuilder aggregation =
        AggregationBuilders
                .percentileRanks("agg")
                .field("height")
                .values(1.24, 1.91, 2.22);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_9">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentileRanks;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
PercentileRanks agg = sr.getAggregations().get("agg");
// For each entry
for (Percentile entry : agg) {
    double percent = entry.getPercent();    // Percent
    double value = entry.getValue();        // Value

    logger.info("percent [{}], value [{}]", percent, value);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">percent [29.664353095090945], value [1.24]
percent [73.9335313461868], value [1.91]
percent [94.40095147327283], value [2.22]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-cardinality">Cardinality Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-cardinality-aggregation.html[Cardinality Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_10">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">CardinalityAggregationBuilder aggregation =
        AggregationBuilders
                .cardinality("agg")
                .field("tags");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_10">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.cardinality.Cardinality;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Cardinality agg = sr.getAggregations().get("agg");
long value = agg.getValue();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-geobounds">Geo Bounds Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-geobounds-aggregation.html[Geo Bounds Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_11">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">GeoBoundsAggregationBuilder aggregation =
        GeoBoundsAggregationBuilder
                .geoBounds("agg")
                .field("address.location")
                .wrapLongitude(true);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_11">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.metrics.geobounds.GeoBounds;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
GeoBounds agg = sr.getAggregations().get("agg");
GeoPoint bottomRight = agg.bottomRight();
GeoPoint topLeft = agg.topLeft();
logger.info("bottomRight {}, topLeft {}", bottomRight, topLeft);</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">bottomRight [40.70500764381921, 13.952946866893775], topLeft [53.49603022435221, -4.190029308156676]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-tophits">Top Hits Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-top-hits-aggregation.html[Top Hits Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_12">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
    AggregationBuilders
        .terms("agg").field("gender")
        .subAggregation(
            AggregationBuilders.topHits("top")
        );</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use most of the options available for standard search such as <code>from</code>, <code>size</code>, <code>sort</code>, <code>highlight</code>, <code>explain</code>&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
    AggregationBuilders
        .terms("agg").field("gender")
        .subAggregation(
            AggregationBuilders.topHits("top")
                .explain(true)
                .size(1)
                .from(10)
        );</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_12">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Terms agg = sr.getAggregations().get("agg");

// For each entry
for (Terms.Bucket entry : agg.getBuckets()) {
    String key = entry.getKey();                    // bucket key
    long docCount = entry.getDocCount();            // Doc count
    logger.info("key [{}], doc_count [{}]", key, docCount);

    // We ask for top_hits for each bucket
    TopHits topHits = entry.getAggregations().get("top");
    for (SearchHit hit : topHits.getHits().getHits()) {
        logger.info(" -&gt; id [{}], _source [{}]", hit.getId(), hit.getSourceAsString());
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce for the first example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [male], doc_count [5107]
 -&gt; id [AUnzSZze9k7PKXtq04x2], _source [{"gender":"male",...}]
 -&gt; id [AUnzSZzj9k7PKXtq04x4], _source [{"gender":"male",...}]
 -&gt; id [AUnzSZzl9k7PKXtq04x5], _source [{"gender":"male",...}]
key [female], doc_count [4893]
 -&gt; id [AUnzSZzM9k7PKXtq04xy], _source [{"gender":"female",...}]
 -&gt; id [AUnzSZzp9k7PKXtq04x8], _source [{"gender":"female",...}]
 -&gt; id [AUnzSZ0W9k7PKXtq04yS], _source [{"gender":"female",...}]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-metrics-scripted-metric">Scripted Metric Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-metrics-scripted-metric-aggregation.html[Scripted Metric Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_13">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ScriptedMetricAggregationBuilder aggregation = AggregationBuilders
    .scriptedMetric("agg")
    .initScript(new Script("params._agg.heights = []"))
    .mapScript(new Script("params._agg.heights.add(doc.gender.value == 'male' ? doc.height.value : -1.0 * doc.height.value)"));</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also specify a <code>combine</code> script which will be executed on each shard:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ScriptedMetricAggregationBuilder aggregation = AggregationBuilders
    .scriptedMetric("agg")
    .initScript(new Script("params._agg.heights = []"))
    .mapScript(new Script("params._agg.heights.add(doc.gender.value == 'male' ? doc.height.value : -1.0 * doc.height.value)"))
    .combineScript(new Script("double heights_sum = 0.0; for (t in params._agg.heights) { heights_sum += t } return heights_sum"));</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also specify a <code>reduce</code> script which will be executed on the node which gets the request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ScriptedMetricAggregationBuilder aggregation = AggregationBuilders
    .scriptedMetric("agg")
    .initScript(new Script("params._agg.heights = []"))
    .mapScript(new Script("params._agg.heights.add(doc.gender.value == 'male' ? doc.height.value : -1.0 * doc.height.value)"))
    .combineScript(new Script("double heights_sum = 0.0; for (t in params._agg.heights) { heights_sum += t } return heights_sum"))
    .reduceScript(new Script("double heights_sum = 0.0; for (a in params._aggs) { heights_sum += a } return heights_sum"));</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_13">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
ScriptedMetric agg = sr.getAggregations().get("agg");
Object scriptedResult = agg.aggregation();
logger.info("scriptedResult [{}]", scriptedResult);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that the result depends on the script you built.
For the first example, this will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">scriptedResult object [ArrayList]
scriptedResult [ {
"heights" : [ 1.122218480146643, -1.8148918111233887, -1.7626731575142909, ... ]
}, {
"heights" : [ -0.8046067304119863, -2.0785486707864553, -1.9183567430207953, ... ]
}, {
"heights" : [ 2.092635728868694, 1.5697545960886536, 1.8826954461968808, ... ]
}, {
"heights" : [ -2.1863201099468403, 1.6328549117346856, -1.7078288405893842, ... ]
}, {
"heights" : [ 1.6043904836424177, -2.0736538674414025, 0.9898266674373053, ... ]
} ]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The second example will produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">scriptedResult object [ArrayList]
scriptedResult [-41.279615707402876,
                -60.88007362339038,
                38.823270659734256,
                14.840192739445632,
                11.300902755741326]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The last example will produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">scriptedResult object [Double]
scriptedResult [2.171917696507009]</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_bucket_aggregations">Bucket aggregations</h3>
<div class="sect3">
<h4 id="java-aggs-bucket-global">Global Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-global-aggregation.html[Global Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_14">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .global("agg")
    .subAggregation(AggregationBuilders.terms("genders").field("gender"));</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_14">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.global.Global;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Global agg = sr.getAggregations().get("agg");
agg.getDocCount(); // Doc count</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-filter">Filter Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-filter-aggregation.html[Filter Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_15">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .filter("agg", QueryBuilders.termQuery("gender", "male"));</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_15">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.filter.Filter;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Filter agg = sr.getAggregations().get("agg");
agg.getDocCount(); // Doc count</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-filters">Filters Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-filters-aggregation.html[Filters Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_16">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
    AggregationBuilders
        .filters("agg",
            new FiltersAggregator.KeyedFilter("men", QueryBuilders.termQuery("gender", "male")),
            new FiltersAggregator.KeyedFilter("women", QueryBuilders.termQuery("gender", "female")));</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_16">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.filters.Filters;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Filters agg = sr.getAggregations().get("agg");

// For each entry
for (Filters.Bucket entry : agg.getBuckets()) {
    String key = entry.getKeyAsString();            // bucket key
    long docCount = entry.getDocCount();            // Doc count
    logger.info("key [{}], doc_count [{}]", key, docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [men], doc_count [4982]
key [women], doc_count [5018]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-missing">Missing Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-missing-aggregation.html[Missing Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_17">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders.missing("agg").field("gender");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_17">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.missing.Missing;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Missing agg = sr.getAggregations().get("agg");
agg.getDocCount(); // Doc count</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-nested">Nested Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-nested-aggregation.html[Nested Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_18">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .nested("agg", "resellers");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_18">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.nested.Nested;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Nested agg = sr.getAggregations().get("agg");
agg.getDocCount(); // Doc count</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-reverse-nested">Reverse Nested Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-reverse-nested-aggregation.html[Reverse Nested Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_19">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
    AggregationBuilders
        .nested("agg", "resellers")
        .subAggregation(
                AggregationBuilders
                        .terms("name").field("resellers.name")
                        .subAggregation(
                                AggregationBuilders
                                        .reverseNested("reseller_to_product")
                        )
        );</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_19">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Nested agg = sr.getAggregations().get("agg");
Terms name = agg.getAggregations().get("name");
for (Terms.Bucket bucket : name.getBuckets()) {
    ReverseNested resellerToProduct = bucket.getAggregations().get("reseller_to_product");
    resellerToProduct.getDocCount(); // Doc count
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-children">Children Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-children-aggregation.html[Children Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_20">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
    AggregationBuilders
        .children("agg", "reseller"); <b class="conum">(1)</b></code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p><code>"agg"</code> is the name of the aggregation and <code>"reseller"</code> is the child type</p>
</li>
</ol>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_20">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.join.aggregations.Children;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Children agg = sr.getAggregations().get("agg");
agg.getDocCount(); // Doc count</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-terms">Terms Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-terms-aggregation.html[Terms Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_21">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .terms("genders")
    .field("gender");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_21">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.terms.Terms;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Terms genders = sr.getAggregations().get("genders");

// For each entry
for (Terms.Bucket entry : genders.getBuckets()) {
    entry.getKey();      // Term
    entry.getDocCount(); // Doc count
}</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_order">Order</h5>
<div class="paragraph">
<p>Import bucket ordering strategy classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.BucketOrder;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Ordering the buckets by their <code>doc_count</code> in an ascending manner:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .terms("genders")
    .field("gender")
    .order(BucketOrder.count(true))</code></pre>
</div>
</div>
<div class="paragraph">
<p>Ordering the buckets alphabetically by their terms in an ascending manner:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .terms("genders")
    .field("gender")
    .order(BucketOrder.key(true))</code></pre>
</div>
</div>
<div class="paragraph">
<p>Ordering the buckets by single value metrics sub-aggregation (identified by the aggregation name):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .terms("genders")
    .field("gender")
    .order(BucketOrder.aggregation("avg_height", false))
    .subAggregation(
        AggregationBuilders.avg("avg_height").field("height")
    )</code></pre>
</div>
</div>
<div class="paragraph">
<p>Ordering the buckets by multiple criteria:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilders
    .terms("genders")
    .field("gender")
    .order(BucketOrder.compound( // in order of priority:
        BucketOrder.aggregation("avg_height", false), // sort by sub-aggregation first
        BucketOrder.count(true))) // then bucket count as a tie-breaker
    .subAggregation(
        AggregationBuilders.avg("avg_height").field("height")
    )</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-significantterms">Significant Terms Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-significantterms-aggregation.html[Significant Terms Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_22">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .significantTerms("significant_countries")
                .field("address.country");

// Let say you search for men only
SearchResponse sr = client.prepareSearch()
        .setQuery(QueryBuilders.termQuery("gender", "male"))
        .addAggregation(aggregation)
        .get();</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_22">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.significant.SignificantTerms;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
SignificantTerms agg = sr.getAggregations().get("significant_countries");

// For each entry
for (SignificantTerms.Bucket entry : agg.getBuckets()) {
    entry.getKey();      // Term
    entry.getDocCount(); // Doc count
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-range">Range Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-range-aggregation.html[Range Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_23">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .range("agg")
                .field("height")
                .addUnboundedTo(1.0f)               // from -infinity to 1.0 (excluded)
                .addRange(1.0f, 1.5f)               // from 1.0 to 1.5 (excluded)
                .addUnboundedFrom(1.5f);            // from 1.5 to +infinity</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_23">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.range.Range;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Range agg = sr.getAggregations().get("agg");

// For each entry
for (Range.Bucket entry : agg.getBuckets()) {
    String key = entry.getKeyAsString();             // Range as key
    Number from = (Number) entry.getFrom();          // Bucket from
    Number to = (Number) entry.getTo();              // Bucket to
    long docCount = entry.getDocCount();    // Doc count

    logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce for the first example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [*-1.0], from [-Infinity], to [1.0], doc_count [9]
key [1.0-1.5], from [1.0], to [1.5], doc_count [21]
key [1.5-*], from [1.5], to [Infinity], doc_count [20]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-daterange">Date Range Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-daterange-aggregation.html[Date Range Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_24">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .dateRange("agg")
                .field("dateOfBirth")
                .format("yyyy")
                .addUnboundedTo("1950")    // from -infinity to 1950 (excluded)
                .addRange("1950", "1960")  // from 1950 to 1960 (excluded)
                .addUnboundedFrom("1960"); // from 1960 to +infinity</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_24">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.range.Range;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Range agg = sr.getAggregations().get("agg");

// For each entry
for (Range.Bucket entry : agg.getBuckets()) {
    String key = entry.getKeyAsString();                // Date range as key
    DateTime fromAsDate = (DateTime) entry.getFrom();   // Date bucket from as a Date
    DateTime toAsDate = (DateTime) entry.getTo();       // Date bucket to as a Date
    long docCount = entry.getDocCount();                // Doc count

    logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, fromAsDate, toAsDate, docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [*-1950], from [null], to [1950-01-01T00:00:00.000Z], doc_count [8]
key [1950-1960], from [1950-01-01T00:00:00.000Z], to [1960-01-01T00:00:00.000Z], doc_count [5]
key [1960-*], from [1960-01-01T00:00:00.000Z], to [null], doc_count [37]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-iprange">Ip Range Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-iprange-aggregation.html[Ip Range Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_25">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder&lt;?&gt; aggregation =
        AggregationBuilders
                .ipRange("agg")
                .field("ip")
                .addUnboundedTo("192.168.1.0")             // from -infinity to 192.168.1.0 (excluded)
                .addRange("192.168.1.0", "192.168.2.0")    // from 192.168.1.0 to 192.168.2.0 (excluded)
                .addUnboundedFrom("192.168.2.0");          // from 192.168.2.0 to +infinity</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you could also use ip masks as ranges:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder&lt;?&gt; aggregation =
        AggregationBuilders
                .ipRange("agg")
                .field("ip")
                .addMaskRange("192.168.0.0/32")
                .addMaskRange("192.168.0.0/24")
                .addMaskRange("192.168.0.0/16");</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_25">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.range.Range;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Range agg = sr.getAggregations().get("agg");

// For each entry
for (Range.Bucket entry : agg.getBuckets()) {
    String key = entry.getKeyAsString();            // Ip range as key
    String fromAsString = entry.getFromAsString();  // Ip bucket from as a String
    String toAsString = entry.getToAsString();      // Ip bucket to as a String
    long docCount = entry.getDocCount();            // Doc count

    logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, fromAsString, toAsString, docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce for the first example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [*-192.168.1.0], from [null], to [192.168.1.0], doc_count [13]
key [192.168.1.0-192.168.2.0], from [192.168.1.0], to [192.168.2.0], doc_count [14]
key [192.168.2.0-*], from [192.168.2.0], to [null], doc_count [23]</code></pre>
</div>
</div>
<div class="paragraph">
<p>And for the second one (using Ip masks):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [192.168.0.0/32], from [192.168.0.0], to [192.168.0.1], doc_count [0]
key [192.168.0.0/24], from [192.168.0.0], to [192.168.1.0], doc_count [13]
key [192.168.0.0/16], from [192.168.0.0], to [192.169.0.0], doc_count [50]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-histogram">Histogram Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-histogram-aggregation.html[Histogram Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_26">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .histogram("agg")
                .field("height")
                .interval(1);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_26">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Histogram agg = sr.getAggregations().get("agg");

// For each entry
for (Histogram.Bucket entry : agg.getBuckets()) {
    Number key = (Number) entry.getKey();   // Key
    long docCount = entry.getDocCount();    // Doc count

    logger.info("key [{}], doc_count [{}]", key, docCount);
}</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_order_2">Order</h5>
<div class="paragraph">
<p>Supports the same order functionality as the <a href="#java-aggs-bucket-terms"><code>Terms Aggregation</code></a>.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-datehistogram">Date Histogram Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-datehistogram-aggregation.html[Date Histogram Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_27">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .dateHistogram("agg")
                .field("dateOfBirth")
                .dateHistogramInterval(DateHistogramInterval.YEAR);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or if you want to set an interval of 10 days:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .dateHistogram("agg")
                .field("dateOfBirth")
                .dateHistogramInterval(DateHistogramInterval.days(10));</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_27">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Histogram agg = sr.getAggregations().get("agg");

// For each entry
for (Histogram.Bucket entry : agg.getBuckets()) {
    DateTime key = (DateTime) entry.getKey();    // Key
    String keyAsString = entry.getKeyAsString(); // Key as String
    long docCount = entry.getDocCount();         // Doc count

    logger.info("key [{}], date [{}], doc_count [{}]", keyAsString, key.getYear(), docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce for the first example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [1942-01-01T00:00:00.000Z], date [1942], doc_count [1]
key [1945-01-01T00:00:00.000Z], date [1945], doc_count [1]
key [1946-01-01T00:00:00.000Z], date [1946], doc_count [1]
...
key [2005-01-01T00:00:00.000Z], date [2005], doc_count [1]
key [2007-01-01T00:00:00.000Z], date [2007], doc_count [2]
key [2008-01-01T00:00:00.000Z], date [2008], doc_count [3]</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_order_3">Order</h5>
<div class="paragraph">
<p>Supports the same order functionality as the <a href="#java-aggs-bucket-terms"><code>Terms Aggregation</code></a>.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-geodistance">Geo Distance Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-geodistance-aggregation.html[Geo Distance Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_28">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .geoDistance("agg", new GeoPoint(48.84237171118314,2.33320027692004))
                .field("address.location")
                .unit(DistanceUnit.KILOMETERS)
                .addUnboundedTo(3.0)
                .addRange(3.0, 10.0)
                .addRange(10.0, 500.0);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_28">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.range.Range;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
Range agg = sr.getAggregations().get("agg");

// For each entry
for (Range.Bucket entry : agg.getBuckets()) {
    String key = entry.getKeyAsString();    // key as String
    Number from = (Number) entry.getFrom(); // bucket from value
    Number to = (Number) entry.getTo();     // bucket to value
    long docCount = entry.getDocCount();    // Doc count

    logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [*-3.0], from [0.0], to [3.0], doc_count [161]
key [3.0-10.0], from [3.0], to [10.0], doc_count [460]
key [10.0-500.0], from [10.0], to [500.0], doc_count [4925]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-aggs-bucket-geohashgrid">Geo Hash Grid Aggregation</h4>
<div class="paragraph">
<p>Here is how you can use
{ref}/search-aggregations-bucket-geohashgrid-aggregation.html[Geo Hash Grid Aggregation]
with Java API.</p>
</div>
<div class="sect4">
<h5 id="_prepare_aggregation_request_29">Prepare aggregation request</h5>
<div class="paragraph">
<p>Here is an example on how to create the aggregation request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AggregationBuilder aggregation =
        AggregationBuilders
                .geohashGrid("agg")
                .field("address.location")
                .precision(4);</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_use_aggregation_response_29">Use aggregation response</h5>
<div class="paragraph">
<p>Import Aggregation definition classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import org.elasticsearch.search.aggregations.bucket.geogrid.GeoHashGrid;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// sr is here your SearchResponse object
GeoHashGrid agg = sr.getAggregations().get("agg");

// For each entry
for (GeoHashGrid.Bucket entry : agg.getBuckets()) {
    String keyAsString = entry.getKeyAsString(); // key as String
    GeoPoint key = (GeoPoint) entry.getKey();    // key as geo point
    long docCount = entry.getDocCount();         // Doc count

    logger.info("key [{}], point {}, doc_count [{}]", keyAsString, key, docCount);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will basically produce:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-text" data-lang="text">key [gbqu], point [47.197265625, -1.58203125], doc_count [1282]
key [gbvn], point [50.361328125, -4.04296875], doc_count [1248]
key [u1j0], point [50.712890625, 7.20703125], doc_count [1156]
key [u0j2], point [45.087890625, 7.55859375], doc_count [1138]
...</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="java-query-dsl">Query DSL</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Elasticsearch provides a full Java query dsl in a similar manner to the
REST {ref}/query-dsl.html[Query DSL]. The factory for query
builders is <code>QueryBuilders</code>. Once your query is ready, you can use the
<a href="#java-search">Search API</a>.</p>
</div>
<div class="paragraph">
<p>To use <code>QueryBuilders</code> just import them in your class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import static org.elasticsearch.index.query.QueryBuilders.*;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you can easily print (aka debug) JSON generated queries using
<code>toString()</code> method on <code>QueryBuilder</code> object.</p>
</div>
<div class="paragraph">
<p>The <code>QueryBuilder</code> can then be used with any API that accepts a query,
such as <code>count</code> and <code>search</code>.</p>
</div>
<div class="sect2">
<h3 id="java-query-dsl-match-all-query">Match All Query</h3>
<div class="paragraph">
<p>See {ref}/query-dsl-match-all-query.html[Match All Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[match_all]</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-full-text-queries">Full text queries</h3>
<div class="paragraph">
<p>The high-level full text queries are usually used for running full text
queries on full text fields like the body of an email. They understand how the
field being queried is analyzed and will apply each field&#8217;s
<code>analyzer</code> (or <code>search_analyzer</code>) to the query string before executing.</p>
</div>
<div class="paragraph">
<p>The queries in this group are:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-match-query"><code>match</code> query</a></dt>
<dd>
<p>The standard query for performing full text queries, including fuzzy matching
and phrase or proximity queries.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-multi-match-query"><code>multi_match</code> query</a></dt>
<dd>
<p>The multi-field version of the <code>match</code> query.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-common-terms-query"><code>common_terms</code> query</a></dt>
<dd>
<p>A more specialized query which gives more preference to uncommon words.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-query-string-query"><code>query_string</code> query</a></dt>
<dd>
<p>Supports the compact Lucene query string syntax,
allowing you to specify AND|OR|NOT conditions and multi-field search
within a single query string. For expert users only.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-simple-query-string-query"><code>simple_query_string</code></a></dt>
<dd>
<p>A simpler, more robust version of the <code>query_string</code> syntax suitable
for exposing directly to users.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-match-query">Match Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-match-query.html[Match Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[match]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>text</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-multi-match-query">Multi Match Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-multi-match-query.html[Multi Match Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[multi_match]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>text</p>
</li>
<li>
<p>fields</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-common-terms-query">Common Terms Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-common-terms-query.html[Common Terms Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[common_terms]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>value</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-query-string-query">Query String Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-query-string-query.html[Query String Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[query_string]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-simple-query-string-query">Simple Query String Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-simple-query-string-query.html[Simple Query String Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[simple_query_string]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-term-level-queries">Term level queries</h3>
<div class="paragraph">
<p>While the <a href="#java-full-text-queries">full text queries</a> will analyze the query
string before executing, the <em>term-level queries</em> operate on the exact terms
that are stored in the inverted index.</p>
</div>
<div class="paragraph">
<p>These queries are usually used for structured data like numbers, dates, and
enums, rather than full text fields.  Alternatively, they allow you to craft
low-level queries, foregoing the analysis process.</p>
</div>
<div class="paragraph">
<p>The queries in this group are:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-term-query"><code>term</code> query</a></dt>
<dd>
<p>Find documents which contain the exact term specified in the field
specified.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-terms-query"><code>terms</code> query</a></dt>
<dd>
<p>Find documents which contain any of the exact terms specified in the field
specified.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-range-query"><code>range</code> query</a></dt>
<dd>
<p>Find documents where the field specified contains values (dates, numbers,
or strings) in the range specified.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-exists-query"><code>exists</code> query</a></dt>
<dd>
<p>Find documents where the field specified contains any non-null value.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-prefix-query"><code>prefix</code> query</a></dt>
<dd>
<p>Find documents where the field specified contains terms which being with
the exact prefix specified.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-wildcard-query"><code>wildcard</code> query</a></dt>
<dd>
<p>Find documents where the field specified contains terms which match the
pattern specified, where the pattern supports single character wildcards
(<code>?</code>) and multi-character wildcards (<code>*</code>)</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-regexp-query"><code>regexp</code> query</a></dt>
<dd>
<p>Find documents where the field specified contains terms which match the
regular expression specified.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-fuzzy-query"><code>fuzzy</code> query</a></dt>
<dd>
<p>Find documents where the field specified contains terms which are fuzzily
similar to the specified term.  Fuzziness is measured as a
<a href="http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance">Levenshtein edit distance</a>
of 1 or 2.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-type-query"><code>type</code> query</a></dt>
<dd>
<p>Find documents of the specified type.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-ids-query"><code>ids</code> query</a></dt>
<dd>
<p>Find documents with the specified type and IDs.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-term-query">Term Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-term-query.html[Term Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[term]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>text</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-terms-query">Terms Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-terms-query.html[Terms Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[terms]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>values</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-range-query">Range Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-range-query.html[Range Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[range]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>from</p>
</li>
<li>
<p>to</p>
</li>
<li>
<p>include lower value means that <code>from</code> is <code>gt</code> when <code>false</code> or <code>gte</code> when <code>true</code></p>
</li>
<li>
<p>include upper value means that <code>to</code> is <code>lt</code> when <code>false</code> or <code>lte</code> when <code>true</code></p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[range_simplified]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>set <code>from</code> to 10 and <code>includeLower</code> to <code>true</code></p>
</li>
<li>
<p>set <code>to</code> to 20 and <code>includeUpper</code> to <code>false</code></p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-exists-query">Exists Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-exists-query.html[Exists Query].</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[exists]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-prefix-query">Prefix Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-prefix-query.html[Prefix Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[prefix]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>prefix</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-wildcard-query">Wildcard Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-wildcard-query.html[Wildcard Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[wildcard]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>wildcard expression</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-regexp-query">Regexp Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-regexp-query.html[Regexp Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[regexp]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>regexp</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-fuzzy-query">Fuzzy Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-fuzzy-query.html[Fuzzy Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[fuzzy]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>text</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-type-query">Type Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-type-query.html[Type Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[type]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>type</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-ids-query">Ids Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-ids-query.html[Ids Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[ids]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>type is optional</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-compound-queries">Compound queries</h3>
<div class="paragraph">
<p>Compound queries wrap other compound or leaf queries, either to combine their
results and scores, to change their behaviour, or to switch from query to
filter context.</p>
</div>
<div class="paragraph">
<p>The queries in this group are:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-constant-score-query"><code>constant_score</code> query</a></dt>
<dd>
<p>A query which wraps another query, but executes it in filter context.  All
matching documents are given the same <code>`constant'' `_score</code>.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-bool-query"><code>bool</code> query</a></dt>
<dd>
<p>The default query for combining multiple leaf or compound query clauses, as
<code>must</code>, <code>should</code>, <code>must_not</code>, or <code>filter</code> clauses.  The <code>must</code> and <code>should</code>
clauses have their scores combined&#8201;&#8212;&#8201;the more matching clauses, the better&#8201;&#8212;&#8201;while the <code>must_not</code> and <code>filter</code> clauses are executed in filter context.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-dis-max-query"><code>dis_max</code> query</a></dt>
<dd>
<p>A query which accepts multiple queries, and returns any documents which match
any of the query clauses.  While the <code>bool</code> query combines the scores from all
matching queries, the <code>dis_max</code> query uses the score of the single best-
matching query clause.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-function-score-query"><code>function_score</code> query</a></dt>
<dd>
<p>Modify the scores returned by the main query with functions to take into
account factors like popularity, recency, distance, or custom algorithms
implemented with scripting.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-boosting-query"><code>boosting</code> query</a></dt>
<dd>
<p>Return documents which match a <code>positive</code> query, but reduce the score of
documents which also match a <code>negative</code> query.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-constant-score-query">Constant Score Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-constant-score-query.html[Constant Score Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[constant_score]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>your query</p>
</li>
<li>
<p>query score
==== Bool Query</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>See {ref}/query-dsl-bool-query.html[Bool Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[bool]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>must query</p>
</li>
<li>
<p>must not query</p>
</li>
<li>
<p>should query</p>
</li>
<li>
<p>a query that must appear in the matching documents but doesn&#8217;t contribute to scoring.
==== Dis Max Query</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>See {ref}/query-dsl-dis-max-query.html[Dis Max Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[dis_max]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>add your queries</p>
</li>
<li>
<p>add your queries</p>
</li>
<li>
<p>boost factor</p>
</li>
<li>
<p>tie breaker
==== Function Score Query</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>See {ref}/query-dsl-function-score-query.html[Function Score Query].</p>
</div>
<div class="paragraph">
<p>To use <code>ScoreFunctionBuilders</code> just import them in your class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.*;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[function_score]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Add a first function based on a query</p>
</li>
<li>
<p>And randomize the score based on a given seed</p>
</li>
<li>
<p>Add another function based on the age field
==== Boosting Query</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>See {ref}/query-dsl-boosting-query.html[Boosting Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[boosting]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>query that will promote documents</p>
</li>
<li>
<p>query that will demote documents</p>
</li>
<li>
<p>negative boost</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-joining-queries">Joining queries</h3>
<div class="paragraph">
<p>Performing full SQL-style joins in a distributed system like Elasticsearch is
prohibitively expensive.  Instead, Elasticsearch offers two forms of join
which are designed to scale horizontally.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-nested-query"><code>nested</code> query</a></dt>
<dd>
<p>Documents may contains fields of type <code>nested</code>. These
fields are used to index arrays of objects, where each object can be queried
(with the <code>nested</code> query) as an independent document.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-has-child-query"><code>has_child</code></a> and <a href="#java-query-dsl-has-parent-query"><code>has_parent</code></a> queries</dt>
<dd>
<p>A parent-child relationship can exist between two
document types within a single index. The <code>has_child</code> query returns parent
documents whose child documents match the specified query, while the
<code>has_parent</code> query returns child documents whose parent document matches the
specified query.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-nested-query">Nested Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-nested-query.html[Nested Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[nested]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>path to nested document</p>
</li>
<li>
<p>your query. Any fields referenced inside the query must use the complete path (fully qualified).</p>
</li>
<li>
<p>score mode could be <code>ScoreMode.Max</code>, <code>ScoreMode.Min</code>, <code>ScoreMode.Total</code>, <code>ScoreMode.Avg</code> or <code>ScoreMode.None</code></p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-has-child-query">Has Child Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-has-child-query.html[Has Child Query]</p>
</div>
<div class="paragraph">
<p>When using the <code>has_child</code> query it is important to use the <code>PreBuiltTransportClient</code> instead of the regular client:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));</code></pre>
</div>
</div>
<div class="paragraph">
<p>Otherwise the parent-join module doesn&#8217;t get loaded and the <code>has_child</code> query can&#8217;t be used from the transport client.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[has_child]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>child type to query against</p>
</li>
<li>
<p>query</p>
</li>
<li>
<p>score mode can be <code>ScoreMode.Avg</code>, <code>ScoreMode.Max</code>, <code>ScoreMode.Min</code>, <code>ScoreMode.None</code> or <code>ScoreMode.Total</code></p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-has-parent-query">Has Parent Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-has-parent-query.html[Has Parent]</p>
</div>
<div class="paragraph">
<p>When using the <code>has_parent</code> query it is important to use the <code>PreBuiltTransportClient</code> instead of the regular client:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));</code></pre>
</div>
</div>
<div class="paragraph">
<p>Otherwise the parent-join module doesn&#8217;t get loaded and the <code>has_parent</code> query can&#8217;t be used from the transport client.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[has_parent]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>parent type to query against</p>
</li>
<li>
<p>query</p>
</li>
<li>
<p>whether the score from the parent hit should propagate to the child hit</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-geo-queries">Geo queries</h3>
<div class="paragraph">
<p>Elasticsearch supports two types of geo data:
<code>geo_point</code> fields which support lat/lon pairs, and
<code>geo_shape</code> fields, which support points, lines, circles, polygons, multi-polygons etc.</p>
</div>
<div class="paragraph">
<p>The queries in this group are:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-geo-shape-query"><code>geo_shape</code></a> query</dt>
<dd>
<p>Find document with geo-shapes which either intersect, are contained by, or
do not intersect with the specified geo-shape.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-geo-bounding-box-query"><code>geo_bounding_box</code></a> query</dt>
<dd>
<p>Finds documents with geo-points that fall into the specified rectangle.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-geo-distance-query"><code>geo_distance</code></a> query</dt>
<dd>
<p>Finds document with geo-points within the specified distance of a central
point.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-geo-polygon-query"><code>geo_polygon</code></a> query</dt>
<dd>
<p>Find documents with geo-points within the specified polygon.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-geo-shape-query">GeoShape Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-geo-shape-query.html[Geo Shape Query]</p>
</div>
<div class="paragraph">
<p>Note: the <code>geo_shape</code> type uses <code>Spatial4J</code> and <code>JTS</code>, both of which are
optional dependencies. Consequently you must add <code>Spatial4J</code> and <code>JTS</code>
to your classpath in order to use this type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;dependency&gt;
    &lt;groupId&gt;org.locationtech.spatial4j&lt;/groupId&gt;
    &lt;artifactId&gt;spatial4j&lt;/artifactId&gt;
    &lt;version&gt;0.6&lt;/version&gt;                        <b class="conum">(1)</b>
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;com.vividsolutions&lt;/groupId&gt;
    &lt;artifactId&gt;jts&lt;/artifactId&gt;
    &lt;version&gt;1.13&lt;/version&gt;                         <b class="conum">(2)</b>
    &lt;exclusions&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;xerces&lt;/groupId&gt;
            &lt;artifactId&gt;xercesImpl&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>check for updates in <a href="http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.locationtech.spatial4j%22%20AND%20a%3A%22spatial4j%22">Maven Central</a></p>
</li>
<li>
<p>check for updates in <a href="http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.vividsolutions%22%20AND%20a%3A%22jts%22">Maven Central</a></p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// Import ShapeRelation and ShapeBuilder
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.builders.ShapeBuilder;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[geo_shape]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>shape</p>
</li>
<li>
<p>relation can be <code>ShapeRelation.CONTAINS</code>, <code>ShapeRelation.WITHIN</code>, <code>ShapeRelation.INTERSECTS</code> or <code>ShapeRelation.DISJOINT</code></p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[indexed_geo_shape]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>The ID of the document that containing the pre-indexed shape.</p>
</li>
<li>
<p>Index type where the pre-indexed shape is.</p>
</li>
<li>
<p>relation</p>
</li>
<li>
<p>Name of the index where the pre-indexed shape is. Defaults to 'shapes'.</p>
</li>
<li>
<p>The field specified as path containing the pre-indexed shape. Defaults to 'shape'.</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-geo-bounding-box-query">Geo Bounding Box Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-geo-bounding-box-query.html[Geo Bounding Box Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[geo_bounding_box]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>bounding box top left point</p>
</li>
<li>
<p>bounding box bottom right point</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-geo-distance-query">Geo Distance Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-geo-distance-query.html[Geo Distance Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[geo_distance]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>center point</p>
</li>
<li>
<p>distance from center point</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-geo-polygon-query">Geo Polygon Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-geo-polygon-query.html[Geo Polygon Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[geo_polygon]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>add your polygon of points a document should fall within</p>
</li>
<li>
<p>initialise the query with field and points</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-specialized-queries">Specialized queries</h3>
<div class="paragraph">
<p>This group contains queries which do not fit into the other groups:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-mlt-query"><code>more_like_this</code> query</a></dt>
<dd>
<p>This query finds documents which are similar to the specified text, document,
or collection of documents.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-script-query"><code>script</code> query</a></dt>
<dd>
<p>This query allows a script to act as a filter.  Also see the
<a href="#java-query-dsl-function-score-query"><code>function_score</code> query</a>.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-percolate-query"><code>percolate</code> query</a></dt>
<dd>
<p>This query finds percolator queries based on documents.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-wrapper-query"><code>wrapper</code> query</a></dt>
<dd>
<p>A query that accepts other queries as json or yaml string.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-mlt-query">More Like This Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-mlt-query.html[More Like This Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[more_like_this]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>fields</p>
</li>
<li>
<p>text</p>
</li>
<li>
<p>ignore threshold</p>
</li>
<li>
<p>max num of Terms in generated queries</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-script-query">Script Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-script-query.html[Script Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[script_inline]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>inlined script</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>If you have stored on each data node a script named <code>myscript.painless</code> with:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-painless" data-lang="painless">doc['num1'].value &gt; params.param1</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use it then with:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[script_file]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Script type: either <code>ScriptType.FILE</code>, <code>ScriptType.INLINE</code> or <code>ScriptType.INDEXED</code></p>
</li>
<li>
<p>Scripting engine</p>
</li>
<li>
<p>Script name</p>
</li>
<li>
<p>Parameters as a <code>Map&lt;String, Object&gt;</code></p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-percolate-query">Percolate Query</h4>
<div class="paragraph">
<p>See:
 * {ref}/query-dsl-percolate-query.html[Percolate Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));</code></pre>
</div>
</div>
<div class="paragraph">
<p>Before the <code>percolate</code> query can be used an <code>percolator</code> mapping should be added and
a document containing a percolator query should be indexed:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">// create an index with a percolator field with the name 'query':
client.admin().indices().prepareCreate("myIndexName")
                        .addMapping("query", "query", "type=percolator")
                        .addMapping("docs", "content", "type=text")
                        .get();

//This is the query we're registering in the percolator
QueryBuilder qb = termQuery("content", "amazing");

//Index the query = register it in the percolator
client.prepareIndex("myIndexName", "query", "myDesignatedQueryName")
    .setSource(jsonBuilder()
        .startObject()
            .field("query", qb) // Register the query
        .endObject())
    .setRefreshPolicy(RefreshPolicy.IMMEDIATE) // Needed when the query shall be available immediately
    .get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>This indexes the above term query under the name
<strong>myDesignatedQueryName</strong>.</p>
</div>
<div class="paragraph">
<p>In order to check a document against the registered queries, use this
code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">//Build a document to check against the percolator
XContentBuilder docBuilder = XContentFactory.jsonBuilder().startObject();
docBuilder.field("content", "This is amazing!");
docBuilder.endObject(); //End of the JSON root object

PercolateQueryBuilder percolateQuery = new PercolateQueryBuilder("query", "docs", docBuilder.bytes());

// Percolate, by executing the percolator query in the query dsl:
SearchResponse response = client().prepareSearch("myIndexName")
        .setQuery(percolateQuery))
        .get();
//Iterate over the results
for(SearchHit hit : response.getHits()) {
    // Percolator queries as hit
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-wrapper-query">Wrapper Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-wrapper-query.html[Wrapper Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[wrapper]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>query defined as query builder</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-span-queries">Span queries</h3>
<div class="paragraph">
<p>Span queries are low-level positional queries which provide expert control
over the order and proximity of the specified terms. These are typically used
to implement very specific queries on legal documents or patents.</p>
</div>
<div class="paragraph">
<p>Span queries cannot be mixed with non-span queries (with the exception of the <code>span_multi</code> query).</p>
</div>
<div class="paragraph">
<p>The queries in this group are:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="#java-query-dsl-span-term-query"><code>span_term</code> query</a></dt>
<dd>
<p>The equivalent of the <a href="#java-query-dsl-term-query"><code>term</code> query</a> but for use with
other span queries.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-multi-term-query"><code>span_multi</code> query</a></dt>
<dd>
<p>Wraps a <a href="#java-query-dsl-term-query"><code>term</code></a>, <a href="#java-query-dsl-range-query"><code>range</code></a>,
<a href="#java-query-dsl-prefix-query"><code>prefix</code></a>, <a href="#java-query-dsl-wildcard-query"><code>wildcard</code></a>,
<a href="#java-query-dsl-regexp-query"><code>regexp</code></a>, or <a href="#java-query-dsl-fuzzy-query"><code>fuzzy</code></a> query.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-first-query"><code>span_first</code> query</a></dt>
<dd>
<p>Accepts another span query whose matches must appear within the first N
positions of the field.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-near-query"><code>span_near</code> query</a></dt>
<dd>
<p>Accepts multiple span queries whose matches must be within the specified distance of each other, and possibly in the same order.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-or-query"><code>span_or</code> query</a></dt>
<dd>
<p>Combines multiple span queries&#8201;&#8212;&#8201;returns documents which match any of the
specified queries.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-not-query"><code>span_not</code> query</a></dt>
<dd>
<p>Wraps another span query, and excludes any documents which match that query.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-containing-query"><code>span_containing</code> query</a></dt>
<dd>
<p>Accepts a list of span queries, but only returns those spans which also match a second span query.</p>
</dd>
<dt class="hdlist1"><a href="#java-query-dsl-span-within-query"><code>span_within</code> query</a></dt>
<dd>
<p>The result from a single span query is returned as long is its span falls
within the spans returned by a list of other span queries.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-term-query">Span Term Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-term-query.html[Span Term Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_term]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>field</p>
</li>
<li>
<p>value</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-multi-term-query">Span Multi Term Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-multi-term-query.html[Span Multi Term Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_multi]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Can be any builder extending the <code>MultiTermQueryBuilder</code> class. For example: <code>FuzzyQueryBuilder</code>,
<code>PrefixQueryBuilder</code>, <code>RangeQueryBuilder</code>, <code>RegexpQueryBuilder</code> or <code>WildcardQueryBuilder</code>.</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-first-query">Span First Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-first-query.html[Span First Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_first]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>query</p>
</li>
<li>
<p>max end position</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-near-query">Span Near Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-near-query.html[Span Near Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_near]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>span term queries</p>
</li>
<li>
<p>slop factor: the maximum number of intervening unmatched positions</p>
</li>
<li>
<p>whether matches are required to be in-order</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-or-query">Span Or Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-or-query.html[Span Or Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_or]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>span term queries</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-not-query">Span Not Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-not-query.html[Span Not Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_not]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>span query whose matches are filtered</p>
</li>
<li>
<p>span query whose matches must not overlap those returned</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-containing-query">Span Containing Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-containing-query.html[Span Containing Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_containing]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p><code>big</code> part</p>
</li>
<li>
<p><code>little</code> part</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-query-dsl-span-within-query">Span Within Query</h4>
<div class="paragraph">
<p>See {ref}/query-dsl-span-within-query.html[Span Within Query]</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/QueryDSLDocumentationTests.java[span_within]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p><code>big</code> part</p>
</li>
<li>
<p><code>little</code> part</p>
</li>
</ol>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="java-admin">Java API Administration</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Elasticsearch provides a full Java API to deal with administration tasks.</p>
</div>
<div class="paragraph">
<p>To access them, you need to call <code>admin()</code> method from a client to get an <code>AdminClient</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">AdminClient adminClient = client.admin();</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
In the rest of this guide, we will use <code>client.admin()</code>.
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="java-admin-indices">Indices Administration</h3>
<div class="paragraph">
<p>To access indices Java API, you need to call <code>indices()</code> method from an <a href="#java-admin"><code>AdminClient</code></a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">IndicesAdminClient indicesAdminClient = client.admin().indices();</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
In the rest of this guide, we will use <code>client.admin().indices()</code>.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="java-admin-indices-create-index">Create Index</h4>
<div class="paragraph">
<p>Using an <a href="#java-admin-indices"><code>IndicesAdminClient</code></a>, you can create an index with all default settings and no mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().indices().prepareCreate("twitter").get();</code></pre>
</div>
</div>
<h5 id="java-admin-indices-create-index-settings" class="float">Index Settings</h5>
<div class="paragraph">
<p>Each index created can have specific settings associated with it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().indices().prepareCreate("twitter")
        .setSettings(Settings.builder()             <b class="conum">(1)</b>
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
        )
        .get();                                     <b class="conum">(2)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Settings for this index</p>
</li>
<li>
<p>Execute the action and wait for the result</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-admin-indices-put-mapping">Put Mapping</h4>
<div class="paragraph">
<p>The PUT mapping API allows you to add a new type while creating an index:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">include-tagged::/Users/wangbin/src/project/es-translate/elasticsearch-253498229/docs/java-api/../../server/src/test/java/org/elasticsearch/client/documentation/IndicesDocumentationIT.java[index-with-mapping]</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p><a href="#java-admin-indices-create-index">Creates an index</a> called <code>twitter</code></p>
</li>
<li>
<p>It also adds a <code>tweet</code> mapping type.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The PUT mapping API also allows to add a new type to an existing index:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().indices().preparePutMapping("twitter")   <b class="conum">(1)</b>
        .setType("user")                                <b class="conum">(2)</b>
        .setSource("{\n" +                              <b class="conum">(3)</b>
                "  \"properties\": {\n" +
                "    \"name\": {\n" +
                "      \"type\": \"text\"\n" +
                "    }\n" +
                "  }\n" +
                "}")
        .get();

// You can also provide the type in the source document
client.admin().indices().preparePutMapping("twitter")
        .setType("user")
        .setSource("{\n" +
                "    \"user\":{\n" +                        <b class="conum">(4)</b>
                "        \"properties\": {\n" +
                "            \"name\": {\n" +
                "                \"type\": \"text\"\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}")
        .get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Puts a mapping on existing index called <code>twitter</code></p>
</li>
<li>
<p>Adds a <code>user</code> mapping type.</p>
</li>
<li>
<p>This <code>user</code> has a predefined type</p>
</li>
<li>
<p>type can be also provided within the source</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>You can use the same API to update an existing mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().indices().preparePutMapping("twitter")   <b class="conum">(1)</b>
        .setType("user")                                <b class="conum">(2)</b>
        .setSource("{\n" +                              <b class="conum">(3)</b>
                "  \"properties\": {\n" +
                "    \"user_name\": {\n" +
                "      \"type\": \"text\"\n" +
                "    }\n" +
                "  }\n" +
                "}")
        .get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Puts a mapping on existing index called <code>twitter</code></p>
</li>
<li>
<p>Updates the <code>user</code> mapping type.</p>
</li>
<li>
<p>This <code>user</code> has now a new field <code>user_name</code></p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-admin-indices-refresh">Refresh</h4>
<div class="paragraph">
<p>The refresh API allows to explicitly refresh one or more index:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().indices().prepareRefresh().get(); <b class="conum">(1)</b>
client.admin().indices()
        .prepareRefresh("twitter")               <b class="conum">(2)</b>
        .get();
client.admin().indices()
        .prepareRefresh("twitter", "company")   <b class="conum">(3)</b>
        .get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Refresh all indices</p>
</li>
<li>
<p>Refresh one index</p>
</li>
<li>
<p>Refresh many indices</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="java-admin-indices-get-settings">Get Settings</h4>
<div class="paragraph">
<p>The get settings API allows to retrieve settings of index/indices:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">GetSettingsResponse response = client.admin().indices()
        .prepareGetSettings("company", "employee").get();                           <b class="conum">(1)</b>
for (ObjectObjectCursor&lt;String, Settings&gt; cursor : response.getIndexToSettings()) { <b class="conum">(2)</b>
    String index = cursor.key;                                                      <b class="conum">(3)</b>
    Settings settings = cursor.value;                                               <b class="conum">(4)</b>
    Integer shards = settings.getAsInt("index.number_of_shards", null);             <b class="conum">(5)</b>
    Integer replicas = settings.getAsInt("index.number_of_replicas", null);         <b class="conum">(6)</b>
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Get settings for indices <code>company</code> and <code>employee</code></p>
</li>
<li>
<p>Iterate over results</p>
</li>
<li>
<p>Index name</p>
</li>
<li>
<p>Settings for the given index</p>
</li>
<li>
<p>Number of shards for this index</p>
</li>
<li>
<p>Number of replicas for this index
==== Update Indices Settings</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>You can change index settings by calling:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().indices().prepareUpdateSettings("twitter")   <b class="conum">(1)</b>
        .setSettings(Settings.builder()                     <b class="conum">(2)</b>
                .put("index.number_of_replicas", 0)
        )
        .get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Index to update</p>
</li>
<li>
<p>Settings</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2">
<h3 id="java-admin-cluster">Cluster Administration</h3>
<div class="paragraph">
<p>To access cluster Java API, you need to call <code>cluster()</code> method from an <a href="#java-admin"><code>AdminClient</code></a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ClusterAdminClient clusterAdminClient = client.admin().cluster();</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
In the rest of this guide, we will use <code>client.admin().cluster()</code>.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="java-admin-cluster-health">Cluster Health</h4>
<div class="sect4">
<h5 id="java-admin-cluster-health-health">Health</h5>
<div class="paragraph">
<p>The cluster health API allows to get a very simple status on the health of the cluster and also can give you
some technical information about the cluster status per index:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ClusterHealthResponse healths = client.admin().cluster().prepareHealth().get(); <b class="conum">(1)</b>
String clusterName = healths.getClusterName();              <b class="conum">(2)</b>
int numberOfDataNodes = healths.getNumberOfDataNodes();     <b class="conum">(3)</b>
int numberOfNodes = healths.getNumberOfNodes();             <b class="conum">(4)</b>

for (ClusterIndexHealth health : healths.getIndices().values()) { <b class="conum">(5)</b>
    String index = health.getIndex();                       <b class="conum">(6)</b>
    int numberOfShards = health.getNumberOfShards();        <b class="conum">(7)</b>
    int numberOfReplicas = health.getNumberOfReplicas();    <b class="conum">(8)</b>
    ClusterHealthStatus status = health.getStatus();        <b class="conum">(9)</b>
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Get information for all indices</p>
</li>
<li>
<p>Access the cluster name</p>
</li>
<li>
<p>Get the total number of data nodes</p>
</li>
<li>
<p>Get the total number of nodes</p>
</li>
<li>
<p>Iterate over all indices</p>
</li>
<li>
<p>Index name</p>
</li>
<li>
<p>Number of shards</p>
</li>
<li>
<p>Number of replicas</p>
</li>
<li>
<p>Index status</p>
</li>
</ol>
</div>
</div>
<div class="sect4">
<h5 id="java-admin-cluster-health-wait-status">Wait for status</h5>
<div class="paragraph">
<p>You can use the cluster health API to wait for a specific status for the whole cluster or for a given index:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">client.admin().cluster().prepareHealth()            <b class="conum">(1)</b>
        .setWaitForYellowStatus()                   <b class="conum">(2)</b>
        .get();
client.admin().cluster().prepareHealth("company")   <b class="conum">(3)</b>
        .setWaitForGreenStatus()                    <b class="conum">(4)</b>
        .get();

client.admin().cluster().prepareHealth("employee")  <b class="conum">(5)</b>
        .setWaitForGreenStatus()                    <b class="conum">(6)</b>
        .setTimeout(TimeValue.timeValueSeconds(2))  <b class="conum">(7)</b>
        .get();</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Prepare a health request</p>
</li>
<li>
<p>Wait for the cluster being yellow</p>
</li>
<li>
<p>Prepare the health request for index <code>company</code></p>
</li>
<li>
<p>Wait for the index being green</p>
</li>
<li>
<p>Prepare the health request for index <code>employee</code></p>
</li>
<li>
<p>Wait for the index being green</p>
</li>
<li>
<p>Wait at most for 2 seconds</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>If the index does not have the expected status and you want to fail in that case, you need
to explicitly interpret the result:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">ClusterHealthResponse response = client.admin().cluster().prepareHealth("company")
        .setWaitForGreenStatus()    <b class="conum">(1)</b>
        .get();

ClusterHealthStatus status = response.getIndices().get("company").getStatus();
if (!status.equals(ClusterHealthStatus.GREEN)) {
    throw new RuntimeException("Index is in " + status + " state"); <b class="conum">(2)</b>
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Wait for the index being green</p>
</li>
<li>
<p>Throw an exception if not <code>GREEN</code></p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect3">
<h4 id="stored-scripts">Stored Scripts API</h4>
<div class="paragraph">
<p>The stored script API allows one to interact with scripts and templates
stored in Elasticsearch. It can be used to create, update, get,
and delete stored scripts and templates.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">PutStoredScriptResponse response = client.admin().cluster().preparePutStoredScript()
                .setId("script1")
                .setContent(new BytesArray("{\"script\": {\"lang\": \"painless\", \"source\": \"_score * doc['my_numeric_field'].value\"} }"), XContentType.JSON)
                .get();

GetStoredScriptResponse response = client().admin().cluster().prepareGetStoredScript()
                .setId("script1")
                .get();

DeleteStoredScriptResponse response = client().admin().cluster().prepareDeleteStoredScript()
                .setId("script1")
                .get();</code></pre>
</div>
</div>
<div class="paragraph">
<p>To store templates simply use "mustache" for the scriptLang.</p>
</div>
<div class="sect4">
<h5 id="_script_language">Script Language</h5>
<div class="paragraph">
<p>The put stored script API allows one to set the language of the stored script.
If one is not provided the default scripting language will be used.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2018-08-24 10:48:53 CST
</div>
</div>
</body>
</html>